package com.github.shiqiyue.blog.markdown.controller;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.shiqiyue.blog.markdown.controller.base.BaseController;
import com.github.shiqiyue.blog.markdown.entity.Article;
import com.github.shiqiyue.blog.markdown.entity.User;
import com.github.shiqiyue.blog.markdown.service.ArticleService;
import com.github.shiqiyue.blog.markdown.service.UserService;
import com.github.shiqiyue.blog.markdown.vo.rep.base.RepBaseVO;

/***
 * index controller
 * 
 * @author wwy
 *
 */
@Controller
@RequestMapping("/")
public class IndexController extends BaseController {
	
	@Autowired
	private ArticleService articleService;
	
	@Autowired
	private UserService userService;
	
	/***
	 * 首页
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping("/")
	public String indexPage(@RequestParam(name = "page", defaultValue = "0") int page,
			@RequestParam(name = "size", defaultValue = "5") int size, Long userId, Model model) {
		
		Article example = new Article();
		if (userId != null) {
			User articleUser = new User();
			articleUser.setId(userId);
			example.setUser(articleUser);
		}
		Page<Article> articlePage = articleService
				.page(new PageRequest(page, size, new Sort(Direction.DESC, "addDate")), Example.of(example));
		model.addAttribute("articlePage", articlePage);
		return "index";
	}
	
	@GetMapping("register")
	public String registerPage() {
		return "register";
	}
	
	@PostMapping("register")
	@ResponseBody
	public RepBaseVO register(String username, String password, String email) {
		RepBaseVO repVO = new RepBaseVO<>();
		User user = new User();
		user.setUsername(username);
		user.setPassword(password);
		user.setEmail(email);
		user.setAddDate(new Date());
		userService.register(user);
		return repVO.setCommonSuccess();
	}
	
}
